package com.txf.net_okhttp3library;


import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * @author txf
 * @create 2019/1/31 0031
 * @请求
 */
public class HttpRequest {

    public final static String POST = "POST";
    public final static String GET = "GET";
    public final static String PUT = "PUT";
    public final static String DELETE = "DELETE";

    /**
     * 创建普通网络请求
     */
    public static okhttp3.Request createRequest(String url, String requestType, String jsonString) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        okhttp3.Request request = null;

        Request.Builder builder = new Request.Builder().url(url);
        switch (requestType) {
            case POST:
                request = builder.post(RequestBody.create(mediaType, jsonString)).build();
                break;
            case GET:
                request = builder.get().build();
                break;
            case PUT:
                request = builder.put(RequestBody.create(mediaType, jsonString)).build();
                break;
            case DELETE:
                request = builder.delete(RequestBody.create(mediaType, jsonString)).build();
                break;
        }
        return request;
    }

    public static okhttp3.Request createRequest(String url, String requestType) {
        return createRequest(url, requestType, "");
    }

    /**
     * 上传文件请求
     */
    public static okhttp3.Request createRequest(String url, String key, File file) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        RequestBody requestBody = builder
                .setType(MultipartBody.FORM)
                .addFormDataPart(key, file.getName(), fileBody)
                .build();
        okhttp3.Request request = new okhttp3.Request.Builder().
                url(url).
                post(requestBody).
                build();
        return request;
    }

}
